export const lineOptions = {
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross',
      crossStyle: {
        color: '#999'
      }
    }
  },
  toolbox: {
    show: false
    // feature: {
    // dataView: { show: true, readOnly: false },
    // magicType: { show: true, type: ['line', 'bar'] },
    // restore: { show: true },
    // saveAsImage: { show: true }
    // }
  },
  legend: {
    data: []
  },
  xAxis: [
    {
      type: 'category',
      data: [],
      axisPointer: {
        type: 'shadow'
      }
    }
  ],
  yAxis: [
    {
      type: 'value'
    }
  ],
  series: [
    {
      name: '',
      type: 'line',
      data: []
    }
  ]
}

export const pieOptions = {
  tooltip: {
    trigger: 'item'
  },
  legend: {
    top: '5%',
    left: 'center'
  },
  series: [
    {
      name: '',
      type: 'pie',
      radius: ['40%', '70%'],
      avoidLabelOverlap: false,
      data: []
    }
  ]
}

// 根据table数据和config生成echart数据
export const getOptions = (echartConfig: any, data: Array<any>, fields: Array<any>) => {
  let defaultOptions: any = {}
  const config = echartConfig.options
  if (['line', 'bar'].includes(echartConfig.type)) {
    defaultOptions = JSON.parse(JSON.stringify(lineOptions))
    defaultOptions.xAxis = config.xAxis.map((c) => ({
      ...lineOptions.xAxis[0],
      ...c,
      data: data.map((d) => d[c.dataField])
    }))
    defaultOptions.series = config.series.map((c) => {
      return {
        ...lineOptions.series[0],
        ...c,
        name: fields.find((f) => f.key === c.dataField)?.name,
        data: data.map((d) => d[c.dataField])
      }
    })
    if (config.yAxis) {
      defaultOptions.yAxis = config.yAxis
    }
    defaultOptions.legend = {
      data: config.series.map((c) => fields.find((f) => f.key === c.dataField)?.name || c.dataField)
    }
    return defaultOptions
  } else if (echartConfig.type === 'pie') {
    const series = echartConfig.options.series.map((c) => ({
      ...pieOptions.series[0],
      ...c,
      data: c.data ? c.data : data.map((d) => ({ value: d[c.valueField], name: d[c.labelField] }))
    }))
    return { ...defaultOptions, ...pieOptions, series }
  }
}
